package com.jeecg.demo.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 *图片下载的公共方法
 * @author rp
 */
public class ImagesUtil {
    public static void download2(HttpServletResponse response,String urlString, String filename) throws Exception {
        //new一个URL对象  
        URL url = new URL(urlString);  
        //打开链接  
        URLConnection conn = url.openConnection();  
         
        //超时响应时间为5秒  
        conn.setConnectTimeout(5 * 1000);  
        //通过输入流获取图片数据  
        InputStream inStream = conn.getInputStream();  
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性  
        byte[] data = readInputStream(inStream);  
        //new一个文件对象用来保存图片，默认保存当前工程根目录  
        //File imageFile = new File(filename);  
        //创建输出流  
        OutputStream outStream = response.getOutputStream();
        //写入数据  
        outStream.write(data);  
        //关闭输出流  
        outStream.close();  
    }
    
    public static void download(HttpServletResponse response,String urlString, String filename) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
     
        //超时响应时间为10秒  
        con.setConnectTimeout(10 * 1000);  
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        OutputStream os =response.getOutputStream();
        // 开始读取
        while ((len = is.read(bs)) != -1) {
          os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }  
    
    public static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        //创建一个Buffer字符串  
        byte[] buffer = new byte[1024];  
        //每次读取的字符串长度，如果为-1，代表全部读取完毕  
        int len = 0;  
        //使用一个输入流从buffer里把数据读取出来  
        while( (len=inStream.read(buffer)) != -1 ){  
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度  
            outStream.write(buffer, 0, len);  
        }  
        //关闭输入流  
        inStream.close();  
        //把outStream里的数据写入内存  
        return outStream.toByteArray();  
    }
    
    public static void downFile(HttpServletRequest request, HttpServletResponse response,String fileUrl,String fileName){
    	BufferedInputStream bis = null;
    	BufferedOutputStream bos = null;
    	   OutputStream fos = null;
    	   InputStream fis = null;
    	        try {
    	            fis = new FileInputStream(fileUrl);
    	            bis = new BufferedInputStream(fis);
    	            fos = response.getOutputStream();
    	            bos = new BufferedOutputStream(fos);
    	            setFileDownloadHeader(request,response, fileName);
    	            int byteRead = 0;
    	            byte[] buffer = new byte[8192];
    	            while((byteRead=bis.read(buffer,0,8192))!=-1){
    	                bos.write(buffer,0,byteRead);
    	            }
    	            bos.flush();
    	            fis.close();
    	            bis.close();
    	            fos.close();
    	            bos.close();
    	        } catch (Exception e) {
    	        	e.printStackTrace();
    	        }
    	}

    	public static void setFileDownloadHeader(HttpServletRequest request,HttpServletResponse response, String fileName) {
    	   try {
    	       //中文文件名支持
    	       String encodedfileName = null;
    	       String agent = request.getHeader("USER-AGENT");
    	       
    	       if(null != agent && -1 != agent.indexOf("MSIE")){//IE
    	           encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
    	       }else if(null != agent && -1 != agent.indexOf("Mozilla")){
    	           encodedfileName = new String (fileName.getBytes("UTF-8"),"iso-8859-1");
    	       }else{
    	           encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
    	       }
    	       response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
    	   } catch (UnsupportedEncodingException e) {
    	       e.printStackTrace();
    	   }
    	}
    	public static void downloadLocal(HttpServletRequest request,HttpServletResponse response,
    			String fileName,String title,String suffix) 
    		throws FileNotFoundException {
    		
            //title = UtilFunction.convert(title, "gb2312", "ISO8859_1");
    		response.reset();
    		//告诉浏览器输出内容为流
    		response.setContentType("application/octet-stream");
    		/*
    		 * attachment是以附件下载的形式，inline是以线上浏览的形式。
    		 * 当点击“保存”的时候都可以下载，
    		 * 当点击“打开”的时候attachment是在本地机里打开，
    		 * inline是在浏览器里打开。*/
    		response.addHeader("Content-Disposition", "inline;filename=" + title + suffix);
    		OutputStream os = null;
    		BufferedInputStream bis = null;
    		try
    		{
    			InputStream is = new FileInputStream(fileName);
    			bis = new BufferedInputStream(is);
    			response.setContentLength(bis.available());
    			byte[] buf = new byte[1024];
    			int bytes = 0;
    			os = response.getOutputStream();
    			while ((bytes = bis.read(buf)) != -1)
    			{
    				os.write(buf, 0, bytes);
    			}
    		} catch (Exception e)
    		{
    			e.getMessage();
    		} finally
    		{
    			try
    			{
    				if (bis != null)
    				{
    					bis.close();
    				}
    				if (os != null)
    				{
    					os.close();
    				}
    			} catch (IOException e)
    			{
    				e.getMessage();
    			}
    		}
        }
}
